package com.fingard.dsp.bank.directbank.pab01;

import java.util.Calendar;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * @author Cruise
 * @date 2017/1/6
 * @modify 2018/3/20 version 1.0
 */
public class PAB01Balance extends PAB01Base implements IBalance {
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
        retAts.writeStart();

        try {
            PAB01Header bankHeader = new PAB01Header();
            bankHeader.trncode = "4001";
            bankHeader.fourZero = "0000";
            bankHeader.reqSeqNo = p_req7506.reqHeader.transSeqID;

            while (p_req7506.readRecord()) {
                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeader(xmlWriter);

                xmlWriter.writeStartElement("Result");
                xmlWriter.writeElementString("Account", p_req7506.readedDetail.actNum);
                xmlWriter.writeElementString("CcyType", "C");
                xmlWriter.writeElementString("CcyCode", convertCurToBank(p_req7506.readedDetail.actCur));
                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);

                if (tmpStrRet[0].length() == 0) {
                    byte[] retBytes = tmpStrRet[1].getBytes(getCharset());
                    String[] tmpRetArr = new String(retBytes, 87, 106, getCharset()).trim().split(":");
                    String tmpRespCode = tmpRetArr[0];
                    String tmpRespInfo = tmpRetArr[1];

                    if ("000000".equals(tmpRespCode)) {
                        if (tmpStrRet[1].indexOf("<") >= 0) {
                            tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<"));
                        }
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            if (tmpBkReader.read("/Result")) {
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.respInfo = tmpRespInfo;
                                tmpRetDetail.actArea = p_req7506.readedDetail.actArea;
                                tmpRetDetail.actCur = p_req7506.readedDetail.actCur;
                                tmpRetDetail.actNum = p_req7506.readedDetail.actNum;
                                tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("TotalAmount");
                                tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("Balance");
                            }
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = tmpSbMsg.toString();
                        }
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpRespInfo;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpStrRet[1];
                }
            }
            retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(ex.getMessage());
            WriteBankLogLn(ex);
        }

        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7505.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7505.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然日循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                PAB01Header bankHeader = new PAB01Header();
                bankHeader.trncode = "4012";
                bankHeader.fourZero = "0000";
                bankHeader.reqSeqNo = getQryTransID();

                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("Result");
                xmlWriter.writeElementString("Account", p_req7505.actNum);// 账号
                xmlWriter.writeElementString("RptDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));// 钞汇标志
                xmlWriter.writeElementString("Reserve", "");// 币种
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();

                // 发银行
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);

                //解析银行返回响应报文
                byte[] retBytes = tmpStrRet[1].getBytes(getCharset());
                String[] respInfo = new String(retBytes, 87, 106, getCharset()).trim().split(":");
                String tmpRetCode = respInfo[0];
                String tmpRetInfo = respInfo[1];
                if (tmpStrRet[1].indexOf("<") >= 0) {
                    tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<"));
                }
                if (tmpStrRet[0].length() == 0) {

                    if (tmpRetCode != null && tmpRetCode.equals("000000")) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {

                            if (tmpBkReader.read("/Result")) {
                                XElement tmpRetNode = tmpBkReader.readedXElement;

                                RetAtsHisBalDetail tmpRetDetail = new RetAtsHisBalDetail();
                                //交易日期
                                String tmpETYDAT = tmpRetNode.getSingleText("RptDate");
                                if (tmpETYDAT.length() == 8) {
                                    tmpRetDetail.balDate = tmpETYDAT.substring(0, 4) + "-" + tmpETYDAT.substring(4, 6) + "-" + tmpETYDAT.substring(6, 8);
                                } else {
                                    tmpRetDetail.balDate = tmpETYDAT;
                                }
                                //余额
                                tmpRetDetail.actBal = tmpRetNode.getSingleText("HisBalance");
                                retAts.writeRetDetail(tmpRetDetail);
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = "银行返回结果有误，无Result节点";//获取银行返回信息"查询失败，银行返回码："+resultArr[0]
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else if (tmpRetCode != null && tmpRetCode.equals("YQ9971")) {
                        Thread.sleep(3000l);
                    } else if (!(tmpRetCode != null && tmpRetCode.equals("YQ9996"))) {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpRetInfo;//获取银行返回信息"查询失败，银行返回码："+resultArr[0]
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
                tmpCalendarFrom.add(Calendar.DATE, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }

        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1"))

        {
            retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0)

        {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
        }
        retAts.writeEnd();
        return retAts;
    }
}
